<template>
	<div>
		<WithFixedPageContainer
			v-model:page="page"
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange"
		>
			<!-- 搜索表单 -->
			<div class="bg-white p-2 rounded-md">
				<BasicTableFrom :formList="formList" @search="handleSearch">
					<template #menu>
						<el-button type="primary" @click="handleAdd">开单</el-button>
					</template>
				</BasicTableFrom>
			</div>

			<!-- 表格 -->
			<template #table>
				<div class="h-full overflow-auto">
					<BasicTable
						:data="tableData"
						:option="tableColumns"
						v-model:page="page"
						:table-loading="loading"
					>
						<!-- 订单编号插槽 -->
						<template #orderNo="{ row }">
							<el-button type="primary" link @click="handleDetail(row)">
								{{ row.orderNo }}
							</el-button>
						</template>

						<!-- 发货信息插槽 -->
						<template #senderInfo="{ row }">
							<div>联系人：{{ row.senderName }}</div>
							<div>联系电话：{{ row.senderPhone }}</div>
							<div>发货地址：{{ row.senderAddress }}</div>
						</template>

						<!-- 收货信息插槽 -->
						<template #receiverInfo="{ row }">
							<div>联系人：{{ row.receiverName }}</div>
							<div>联系电话：{{ row.receiverPhone }}</div>
							<div>收货地址：{{ row.receiverAddress }}</div>
						</template>

						<!-- 订单状态插槽 -->
						<template #orderStatus="{ row }">
							<el-tag :type="getStatusType(row.orderStatus)">
								{{ row.orderStatus }}
							</el-tag>
						</template>

						<!-- 操作插槽 -->
						<template #menu="{ row }">
							<!-- 默认显示的按钮 -->
							<el-button type="primary" link @click="handleDetail(row)">
								详情
							</el-button>

							<el-button
								type="danger"
								link
								@click="handleCancel(row)"
								v-if="canCancel(row)"
							>
								取消
							</el-button>

							<!-- 更多操作下拉菜单 -->
							<el-dropdown v-if="getMoreActions(row).length > 0">
								<el-button type="primary" link>
									更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
								</el-button>
								<template #dropdown>
									<el-dropdown-menu>
										<el-dropdown-item
											v-for="action in getMoreActions(row)"
											:key="action.name"
											@click="handleAction(action.name, row)"
										>
											{{ action.label }}
										</el-dropdown-item>
									</el-dropdown-menu>
								</template>
							</el-dropdown>
						</template>
					</BasicTable>
				</div>
			</template>
		</WithFixedPageContainer>

		<!-- 开单弹窗 -->
		<OrderDialog
			v-model="dialogVisible"
			:editData="editData"
			@success="handleSuccess"
		/>

		<!-- 详情弹窗 -->
		<OrderDetail
			v-model="detailVisible"
			:detailData="detailData"
			@edit="handleEdit"
		/>

		<!-- 修改地址弹窗 -->
		<ModifyAddressDialog
			v-model="modifyAddressVisible"
			:orderData="currentOrder"
			@success="handleModifyAddressSuccess"
		/>

		<!-- 取消订单弹窗 -->
		<CancelOrderDialog
			v-model="cancelOrderVisible"
			:orderData="currentOrder"
			@success="handleCancelOrderSuccess"
		/>

		<!-- 修改货物信息弹窗 -->
		<ModifyGoodsDialog
			v-model="modifyGoodsVisible"
			:order-data="currentOrder"
			@success="handleModifyGoodsSuccess"
		/>

		<!-- 加急弹框 -->
		<UrgentOrderDialog
			v-model="urgentDialogVisible"
			:orderData="currentOrder"
			@success="handleUrgentSuccess"
		/>
	</div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ArrowDown } from '@element-plus/icons-vue';
import OrderDialog from './components/OrderDialog.vue';
import OrderDetail from './components/OrderDetail.vue';
import ModifyAddressDialog from './components/ModifyAddressDialog.vue';
import CancelOrderDialog from './components/CancelOrderDialog.vue';
import ModifyGoodsDialog from './components/ModifyGoodsDialog.vue';
import UrgentOrderDialog from './components/UrgentOrderDialog.vue';
import { useRouter } from 'vue-router';

// 获取路由实例
const router = useRouter();

// 搜索表单配置
const formList = computed(() => [
	{
		key: 'dateRange',
		type: 'datetimerange',
		label: '运单日期:',
		placeholder: '请选择日期范围',
		inputWidth: 380,

		clearable: true,
		startPlaceholder: '开始时间',
		endPlaceholder: '结束时间',
	},
	{
		key: 'status',
		type: 'select',
		label: '订单状态:',
		placeholder: '请选择状态',
		clearable: true,
		options: [
			{ label: '已确认', value: 'confirmed' },
			{ label: '已派车', value: 'dispatched' },
			{ label: '已装车', value: 'loaded' },
			{ label: '已签收', value: 'signed' },
			{ label: '已完成', value: 'completed' },
		],
	},
	{
		key: 'keyword',
		type: 'input-text',
		label: '关键字:',
		placeholder: '请输入关键字',
		clearable: true,
	},
]);

// 表格列配置
const tableColumns = {
	showOverflowTooltip: true,
	border: true,
	menu: true,
	menuWidth: 180,
	column: [
		{ type: 'selection' },
		{ type: 'index', label: '序号', width: 60, align: 'center' },
		{ prop: 'orderNo', label: '订单编号', minWidth: 140, slot: 'orderNo' },
		{ prop: 'relatedOrderNo', label: '关联运单号', minWidth: 140 },
		{ prop: 'shipType', label: '发运类型', width: 100 },
		{ prop: 'group', label: '团队', width: 120 },
		{ prop: 'customer', label: '客户', width: 120 },
		{
			prop: 'senderInfo',
			label: '发货信息',
			minWidth: 200,
			slot: 'senderInfo',
		},
		{
			prop: 'receiverInfo',
			label: '收货信息',
			minWidth: 200,
			slot: 'receiverInfo',
		},
		{ prop: 'pickupTime', label: '预计装车时间', width: 160 },
		{ prop: 'deliveryTime', label: '预计到达时间', width: 160 },
		{ prop: 'carModel', label: '车型', width: 100 },
		{ prop: 'quantity', label: '件数', width: 80, align: 'right' },
		{ prop: 'weight', label: '重量(kg)', width: 100, align: 'right' },
		{
			prop: 'totalAmount',
			label: '运费合计',
			width: 120,
			align: 'right',
			formatter: (row) => row.totalAmount?.toFixed(2),
		},
		{ prop: 'orderStatus', label: '订单状态', width: 100, slot: 'orderStatus' },
		{ prop: 'orderSource', label: '订单来源', width: 100 },
		{ prop: 'creator', label: '创建人', width: 100 },
		{ prop: 'createTime', label: '创建时间', width: 160 },
	],
};

// 分页配置
const page = reactive({
	total: 0,
	currentPage: 1,
	pageSize: 10,
});

// 表格数据
const tableData = ref([
	{
		orderNo: 'DD20250420001',
		relatedOrderNo: '',
		shipType: '整车运输',
		group: '集装箱（重车）',
		customer: 'XX',
		senderName: '李四',
		senderPhone: '13522222222',
		senderAddress: '四川省成都市青羊区XXX路XXX号',
		receiverName: '王五',
		receiverPhone: '13511111111',
		receiverAddress: '四川省眉山市东坡区XXX路XXX号',
		pickupTime: '2025-04-11 09:00:00',
		deliveryTime: '2025-04-11 14:00:00',
		carModel: '解放J7',
		quantity: 100,
		weight: 4,
		totalAmount: 3050.0,
		orderStatus: '已确认',
		orderSource: '',
		creator: 'admin',
		createTime: '2025-4-22 10:22:22',
	},
]);

// 加载状态
const loading = ref(false);

// 获取状态类型
const getStatusType = (status) => {
	const statusMap = {
		已确认: 'success',
		已派车: 'warning',
		已装车: 'warning',
		已签收: 'info',
		已完成: '',
	};
	return statusMap[status] || 'info';
};

// 搜索
const handleSearch = (data) => {
	console.log('搜索条件：', data);
	// TODO: 调用搜索接口
	getList();
};

// 弹窗控制
const dialogVisible = ref(false);
const editData = ref(null);

// 新增
const handleAdd = () => {
	editData.value = null;
	dialogVisible.value = true;
};

// 编辑
const handleEdit = (row) => {
	editData.value = { ...row };
	dialogVisible.value = true;
};

// 详情弹窗控制
const detailVisible = ref(false);
const detailData = ref(null);

// 详情
const handleDetail = (row) => {
	detailData.value = { ...row };
	detailVisible.value = true;
};

// 删除
const handleDelete = (row) => {
	ElMessageBox.confirm('确认要删除该订单吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			console.log('删除订单：', row);
			ElMessage.success('删除成功');
			getList();
		})
		.catch(() => {});
};

// 分页大小改变
const handleSizeChange = (val) => {
	page.pageSize = val;
	getList();
};

// 当前页改变
const handleCurrentChange = (val) => {
	page.currentPage = val;
	getList();
};

// 获取列表数据
function getList() {
	loading.value = true;
	// TODO: 调用接口获取数据
	setTimeout(() => {
		loading.value = false;
	}, 500);
}

// 初始化加载
getList();

// 保存成功
const handleSuccess = () => {
	getList();
};

// 判断是否可以编辑
const canEdit = (row) => {
	return ['已确认', '调度中'].includes(row.orderStatus);
};

// 判断是否可以取消
const canCancel = (row) => {
	return ['已确认', '调度中', '待取货'].includes(row.orderStatus);
};

// 获取更多操作按钮
const getMoreActions = (row) => {
	const actions = [];

	switch (row.orderStatus) {
		case '已确认':
			actions.push(
				{ name: 'adjustSchedule', label: '调度' },
				{ name: 'modifyAddress', label: '修改收发地址' },
				{ name: 'modifyGoods', label: '修改货物信息' },
				{ name: 'urgent', label: '加急' },
			);
			break;
		case '调度中':
			actions.push(
				{ name: 'modifyAddress', label: '修改收发地址' },
				{ name: 'modifyGoods', label: '修改货物信息' },
				{ name: 'adjustSchedule', label: '重新调度' },
			);
			break;
		case '待取货':
			actions.push(
				{ name: 'modifyAddress', label: '修改收发地址' },
				{ name: 'modifyGoods', label: '修改货物信息' },
			);
			break;
		case '运输中':
			actions.push(
				{ name: 'modifyAddress', label: '修改收货地址' },
				{ name: 'replanRoute', label: '重新规划路线' },
			);
			break;
	}

	return actions;
};

// 修改地址弹窗控制
const modifyAddressVisible = ref(false);
const currentOrder = ref(null);

// 修改地址
const handleModifyAddress = (row) => {
	currentOrder.value = row;
	modifyAddressVisible.value = true;
};

// 修改地址成功
const handleModifyAddressSuccess = () => {
	getList();
};

// 取消订单弹窗控制
const cancelOrderVisible = ref(false);

// 取消订单
const handleCancel = (row) => {
	currentOrder.value = row;
	cancelOrderVisible.value = true;
};

// 取消订单成功
const handleCancelOrderSuccess = () => {
	getList();
};

// 处理操作按钮点击
const handleAction = (actionName, row) => {
	switch (actionName) {
		case 'adjustSchedule':
			handleAdjustSchedule(row);
			break;
		case 'modifyAddress':
			handleModifyAddress(row);
			break;
		case 'modifyGoods':
			handleModifyGoods(row);
			break;
		case 'urgent':
			handleUrgent(row);
			break;
		case 'replanRoute':
			handleReplanRoute(row);
			break;
	}
};

// 调度
const handleAdjustSchedule = (row) => {
	// TODO: 实现调度功能
	console.log('调度订单：', row);
	router.push({
		path: '/dispatch',
		query: {
			orderNo: row.orderNo,
			// 可以添加更多需要传递的参数
		},
	});
};

// 修改货物信息
const modifyGoodsVisible = ref(false);

// 修改货物信息
const handleModifyGoods = (row) => {
	currentOrder.value = row;
	modifyGoodsVisible.value = true;
};

// 修改货物信息成功
const handleModifyGoodsSuccess = () => {
	// TODO: 刷新列表数据
	getList();
};

// 加急弹框控制
const urgentDialogVisible = ref(false);

// 加急
const handleUrgent = (row) => {
	currentOrder.value = row;
	urgentDialogVisible.value = true;
};

// 加急成功
const handleUrgentSuccess = (urgentData) => {
	ElMessage.success('订单已设置为加急');
	getList();
};

// 重新规划路线
const handleReplanRoute = (row) => {
	// TODO: 实现重新规划路线功能
	console.log('重新规划路线：', row);
};
</script>

<style lang="scss" scoped>
.order-management {
	padding: 16px;
	background-color: var(--el-bg-color-page);
	min-height: 100%;
}

:deep(.el-table) {
	--el-table-border-color: var(--el-border-color-lighter);
}
</style>
